import React, { useRef, useState } from 'react';
import { message } from 'antd';

interface CopyToClipboardProps {
  text: string;
  children: React.ReactNode;
  onCopy?: (text: string, result: boolean) => void;
}

/**
 * 自定义复制到剪贴板组件，避免使用findDOMNode
 */
const CopyToClipboard: React.FC<CopyToClipboardProps> = ({
  text,
  children,
  onCopy,
}) => {
  const [copied, setCopied] = useState(false);
  const timeoutRef = useRef<NodeJS.Timeout | null>(null);

  const handleCopy = async () => {
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
    }

    try {
      await navigator.clipboard.writeText(text);
      setCopied(true);
      onCopy?.(text, true);
      message.success('已复制到剪贴板');
      
      timeoutRef.current = setTimeout(() => {
        setCopied(false);
      }, 2000);
    } catch (error) {
      console.error('复制失败:', error);
      onCopy?.(text, false);
      message.error('复制失败');
    }
  };

  return (
    <div onClick={handleCopy} style={{ cursor: 'pointer' }}>
      {typeof children === 'function' ? children(copied) : children}
    </div>
  );
};

export default CopyToClipboard;
